import store from '../utils/store'
import config from '../utils/config'
import VueResource from 'vue-resource'
import _ from 'lodash'
import { event } from '../utils/event'

function makeAuth (session) {
  return session.id
}

function attachAuth (options) {
  options = options || {}
  var session = store.get('session')
  options.headers = options.headers || {}
  if (session) {
    options.headers['Authorization'] = session.id
  }
  return options
}

function logout () {
  store.set('user', '')
  store.set('profile', '')
}

function handleSessionExpire (response) {
  if (response.status === 401) {
    logout()
    console.log('User Session Expired!')
    var excludesPaths = ['/logout', '/callback']
    if (!_.includes(excludesPaths, window.location.pathname)) {
      var newPath = window.location.href.split(window.location.host)[1]
      store.set('next', newPath)
    }
    event.emit('goto-login')
  }
  return Promise.reject(response)
}

// const ms = ''
// const iam = ''
class Api {
  constructor (config, Vue) {
    this.APIHOST = config.APIHOST
    this.http = Vue.http
    this.resource = Vue.resource
    this.$message = function (message) {
      Vue.prototype.$message.call(this, message)
    }
  }

  request (method, path, params, options) {
    const opts = Object.assign({ errorShow: true }, options || {})
    method = method.toLowerCase()
    var promise
    if (method === 'get' || method === 'delete') {
      promise = this.http[method](this.APIHOST + path, attachAuth({ params }))
    } else {
      promise = this.http[method](this.APIHOST + path, params, attachAuth())
    }
    return promise
      .then(
        response => {
          if (response.status >= 200 && response.status <= 399) {
            return response.json()
          } else {
            if (response.status === 401) {
              this.$message({
                type: 'error',
                message: '您的认证已经过期，请重新登录'
              })
              return handleSessionExpire({ status: 401 })
            } else {
              opts.errorShow && this.$message({
                type: 'error',
                message: 'API 请求失败，请稍后重试'
              })
              return Promise.reject(response)
            }
          }
        },
        error => {
          console.error('请求失败: ', error)
          var message =
            error && error.body && (error.body.message || error.body.msg)
          if (opts.errorShow) {
            if (message) {
              message = '请求失败: ' + message
            } else {
              message = '网络请求失败，请稍后重试'
            }
            this.$message({
              type: 'error',
              message: message,
              duration: 5000
            })
          }
          return Promise.reject(error)
        }
      )
      .catch(handleSessionExpire)
  }

  get () {
    return this.request.apply(this, _.concat(['get'], arguments))
  }

  post () {
    return this.request.apply(this, _.concat(['post'], arguments))
  }

  put () {
    return this.request.apply(this, _.concat(['put'], arguments))
  }

  delete () {
    return this.request.apply(this, _.concat(['delete'], arguments))
  }

  patch () {
    return this.request.apply(this, _.concat(['patch'], arguments))
  }

  attachAuthforXhr (xhr) {
    var user = store.get('user')
    if (user) {
      return xhr.setRequestHeader('Authorization', makeAuth(user))
    }
  }

  // login (email, password) {
  //   return this.http
  //     .post(this.APIHOST + '/session', {
  //       email,
  //       password
  //     })
  //     .then(response => {
  //       if (response.status >= 200 && response.status < 300) {
  //         return response.json()
  //       } else {
  //         if (response.status === 401) {
  //           return handleSessionExpire({ status: 401 })
  //         } else {
  //           return Promise.reject(response)
  //         }
  //       }
  //     })
  //     .catch(handleSessionExpire)
  // }

  // logout () {
  //   return this.request('delete', '/session')
  //     .then(function (response) {
  //       store.set('user', '')
  //     })
  //     .catch(() => {
  //       store.set('user', '')
  //     })
  // }

  getUser () {
    // return this.get('/session/userinfo')
    return Promise.resolve({
      username: 'abc'
    })
  }

  //
  getShowList (data) {
    // return this.get('/show', data)
    return Promise.resolve({
      result: [
        {
          id: 1,
          name: 'aaa',
          overview: 'aaaaaaaa',
          description: 'aaaaaaaaaaaaaaaaaaaaaaaaa'
        },
        {
          id: 2,
          name: 'bbb',
          overview: 'bbbbbbbbb',
          description: 'bbbbbbbbbbbbbbbbbbbbbbbbb'
        },
        {
          id: 3,
          name: 'ccc',
          overview: 'ccccccccc',
          description: 'cccccccccccccccccccccccccc'
        }
      ],
      total: 3
    })
  }
  getShowDetail (id) {
    // return this.get('/show/' + id)
    return Promise.resolve({
      id: 1,
      name: 'aaa',
      overview: 'aaaaaaaa',
      description: 'aaaaaaaaaaaaaaaaaaaaaaaaa'
    })
  }
  addShowMes (Show) {
    // return this.post('/show', Show)
    return Promise.resolve({
      message: 'ok'
    })
  }
  editShowMes (Show) {
    // return this.put('/show', Show)
    return Promise.resolve({
      message: 'ok'
    })
  }
  deleteShowMes (id) {
    // return this.delete('/show/' + id)
    return Promise.resolve({
      message: 'ok'
    })
  }
}

function install (Vue) {
  Vue.use(VueResource)
  Vue.prototype.api = new Api(config, Vue)
}

export default {
  install
}
